Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Solution:

  1. public class Solution {
  2. public int minPathSum(int[][] grid) {
  3. int n = grid.length, m = grid[0].length;
  4. int[][] dp = new int[n][m];
  5. dp[0][0] = grid[0][0];
  6. // first row
  7. for (int j = 1; j < m; j++)
  8. dp[0][j] = grid[0][j] + dp[0][j - 1];
  9. // first col
  10. for (int i = 1; i < n; i++)
  11. dp[i][0] = grid[i][0] + dp[i - 1][0];
  12. for (int i = 1; i < n; i++) {
  13. for (int j = 1; j < m; j++) {
  14. dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]);
  15. }
  16. }
  17. return dp[n - 1][m - 1];
  18. }
  19. }